/blog/archive/
Diving into Rocket
Here are some source files I implemented to get this web page started, it diverges just a little from a couple of different tutorials I followed to get things working. I’ve added some excessive comments to help annotate how I think things work(being new to Rust, I can’t be certain of correctness).
How this differs from the default Rocket tutorial
Added Templates
Passing data through our template files is a pretty basic improvement so we can reuse HTML and easily take advantage of dynamic data sources.
The templates are not processed at compile time so we can work on them in real time to dramatically speed up web development in Rust.
Added Static Files
Setting certain files as passthrough objects, like css, javascript and images. Lets us work on them in real time much like the templates, there is also no reason yet to work with these files programatically.
Otherwise this is still a super basic implementation of Rocket that I’ll be building on to flesh out this blog.
Cargo.toml
[dependencies]
rocket = "0.4.4"
serde = "1.0.105"
serde_derive = "1.0.105"
tera = "1.2.0"
[dependencies.rocket_contrib]
version = "0.4.4"
default-features = false
features = ["tera_templates", "serve"]
src/main.rs
#![feature(proc_macro_hygiene, decl_macro)]
use rocket_contrib::templates::Template;
use rocket_contrib::serve::StaticFiles;
extern crate rocket_contrib;
#[macro_use] extern crate rocket;
#[macro_use] extern crate serde_derive;
#[derive(Serialize)]
pub struct Post {
id: i32,
title: String,
body: String,
}
fn main() {
rocket::ignite()
.attach(Template::fairing())
.mount("/", routes![index])
.mount("/static", StaticFiles::from(concat!(env!("CARGO_MANIFEST_DIR"), "/static")))
.launch();
}
#[get("/")]
fn index() -> Template {
let context = Post {
id: 0,
title: String::from("This"),
body: String::from("works"),
};
Template::render("front", &context)
}
And a couple of template files, one as a base for all pages and the front for our test content delivery.
templates/base.tera
<!doctype html>
<html>
<head>
<link rel="stylesheet" href="/static/css/main.css">
</head>
<body>
{% block content %}
{% endblock content %}
</body>
</html>
templates/front.tera
{% extends "base" %}
{% block content %}
This is a tera template.
<h1>{{ title }}</h1>
<p>{{ body }}</p>
{% endblock content %}
So our directory should look something like this.
.
├── Cargo.lock
├── Cargo.toml
├── src
│ └── main.rs
├── static
│ ├── css
│ │ └── main.css
│ ├── images
│ └── js
└── templates
├── base.tera
└── front.tera